import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Modal } from 'antd';
import { toJS } from 'mobx';
import { Condition, getAdButtons } from './list/listCondition';
import { WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { WeaRightMenu, WeaTop, WeaTab, WeaErrorPage, WeaTools } from 'ecCom';
import ContractOperateDialog from './contract/contractOperate';
import { locale } from 'moment';
import { WeaLocaleProvider } from 'ecCom';
import * as Apis from '../apis/contractManage';

const getLabel = WeaLocaleProvider.getLabel;

@inject('contractManageStore')
@observer
class ContractManage extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.doInit(this.props);
  }
  doInit(props) {
    const { location, contractManageStore } = props;
    const { initDatas, doSearch, initTabs, getContractRightMenu } = contractManageStore;
    let params = {};
    const query = location.query;
    // if(JSON.stringify(query)==="{}"){
    //     params= {};
    // }else{
    //     params={...query,fromType:1, tabType:"all"};
    //     getContractRightMenu({selectType:'contractinfo',customerId:query.customerId});  //卡片合同  右键
    // }
    if (query && query.customerId) {
      params = { ...query, fromType: 1, tabType: 'all' };
      getContractRightMenu({ selectType: 'contractinfo', customerId: query.customerId }); // 卡片合同  右键
    } else {
      // params= {};
    }
    initTabs(params);
    initDatas(params);
    doSearch(params);
  }
  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    // 点击菜单路由刷新组件
    if (keyOld !== keyNew) {
      const { contractManageStore, location } = nextProps;
      const { initDatas, doSearch, initTabs } = contractManageStore;
      contractManageStore.clearStatus();
      const query = location.query;
      let params = {};
      if (query && query.customerId) {
        params = { ...query, fromType: 1 };
      }
      // let params = {};
      // if(JSON.stringify(query)==="{}"){
      //     params= {};
      // }else{
      //     params={...query,fromType:1};
      // }
      initTabs(params);
      initDatas(params);
      doSearch(params);
    }
  }
  componentWillUnmount() {
    const { contractManageStore } = this.props;
    contractManageStore.clearStatus();
  }
  render() {
    const { contractManageStore, location } = this.props;
    const { title, loading, tableStore, showSearchAd, form, remindCount, baseParams, remindTableStore, tabDatas, reLoad } = contractManageStore;
    const formParams = form.getFormParams() || {};
    const query = location.query;
    if (query && query.customerId) {
      return (
        <div>
          <WeaTab
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@86p8yh`}
            buttonsAd={getAdButtons(contractManageStore, this.props.ecId || '')}
            searchType={['base', 'advanced']}
            searchsBaseValue={formParams.name}
            setShowSearchAd={(bool) => { contractManageStore.setShowSearchAd(bool); }}
            hideSearchAd={() => contractManageStore.setShowSearchAd(false)}
            searchsAd={
              <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@j0xocu`} listStore={contractManageStore} form={form} onEnterSearch={this.onEnterSearch} /></div>
            }
            showSearchAd={showSearchAd}
            onSearch={(v) => { contractManageStore.doSearch(); }}
            onSearchChange={(v) => {
              if (contractManageStore.form.has('name')) {
                contractManageStore.appendFormFields({ name: { value: v } });
              } else {
                contractManageStore.form.add(v, { key: 'name' });
              }
            }}
          />
          <WeaTable
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@zg6v3v`}
            comsWeaTableStore={tableStore}
            hasOrder
            needScroll
            register_table={reLoad}
            onOperatesClick={this.onOperatesClick.bind(this)}
            getColumns={c => this.reRenderColumns(c)}
          />
          <ContractOperateDialog ecId={`${this && this.props && this.props.ecId || ''}_ContractOperateDialog@1gihoi`} contentStore={contractManageStore} location={location} />
        </div>
      );
    }
    return (
      <WeaRightMenu
        ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@hwqaqg`}
        datas={this.getRightMenu()}
        onClick={this.onRightMenuClick.bind(this)}
        collectParams={{
          favname: getLabel(16260, '合同管理'),
          favouritetype: 4,
          importantlevel: 1,
          objid: -1,
        }}
      >
        <WeaTop
          ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@d6nlfs`}
          title={getLabel(16260, '合同管理')}
          loading={loading}
          icon={<i className="icon-coms-crm" />}
          iconBgcolor="#96358a"
          buttons={[]}
          buttonSpace={10}
          showDropIcon
          dropMenuDatas={this.getRightMenu()}
          onDropMenuClick={this.onRightMenuClick.bind(this)}
        >
          <WeaTab
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@8sbsd0`}
            buttonsAd={getAdButtons(contractManageStore, this.props.ecId || '')}
            searchType={['base', 'advanced']}
            searchsBaseValue={formParams.name}
            setShowSearchAd={(bool) => { contractManageStore.setShowSearchAd(bool); }}
            hideSearchAd={() => contractManageStore.setShowSearchAd(false)}
            searchsAd={
              <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@8fshsn`} listStore={contractManageStore} form={form} onEnterSearch={this.onEnterSearch} /></div>
            }
            showSearchAd={showSearchAd}
            onSearch={(v) => { contractManageStore.doSearch(); }}
            onSearchChange={(v) => { contractManageStore.appendFormFields({ name: { value: v } }); }}
            selectedKey={baseParams.tabType}
            keyParam="key" // 主键
            onChange={this.changeData.bind(this)}
            datas={toJS(tabDatas)}
          />
          <WeaTable
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@91htfy`}
            comsWeaTableStore={tableStore}
            hasOrder
            needScroll
            register_table={reLoad}
            onOperatesClick={this.onOperatesClick.bind(this)}
            getColumns={c => this.reRenderColumns(c)}
          />
          <ContractOperateDialog ecId={`${this && this.props && this.props.ecId || ''}_ContractOperateDialog@xmiq9p`} contentStore={contractManageStore} location={location} />
        </WeaTop>
      </WeaRightMenu>
    );
  }
  getRightMenu() {
    const btns = [];
    btns.push({
    		icon: <i className="icon-coms-search " />,
      content: getLabel(197, '搜索'),
      key: 0,
    });
    btns.push({
    		icon: <i className="icon-coms-Custom " />,
      content: getLabel(382660, '显示定制列'),
      key: 1,
    	});
    	return btns;
  }
  onRightMenuClick(key) {
    const { contractManageStore } = this.props;
    if (key == '0') {
      contractManageStore.doSearch();
    }
    if (key == '1') {
      contractManageStore.onShowColumn();
    }
  }
  changeData(key) {
    const { doSearch, setShowSearchAd } = this.props.contractManageStore;
    setShowSearchAd(false);
    doSearch({ tabType: key });
  }
  onOperatesClick(record, index, operate, flag) {
    const { contractManageStore } = this.props;
    const { complete, sign, approveInfo, getContractInfo, getExchangeList, getContractShareList, deleteContract, canEdit, getFormCondition } = contractManageStore;

    if (flag == '6') { // 设置共享
      getFormCondition();
      getContractShareList({ contractId: record.randomFieldId }, '3', true);
    }
    if (flag == '5') { // 相关交流
      getExchangeList({ contractId: record.randomFieldId }, '2', true);
    }
    if (flag == '4') { // 合同打开
      getContractInfo({ contractId: record.randomFieldId, operation: record.status == '2' ? 'edit' : 'view' }, '1', true, record.status);
    }
    if (flag == '2') { // 签单
      sign(record.randomFieldId, 'operate');
    }
    if (flag == '3') { // 执行完成
      complete(record.randomFieldId, 'operate');
    }
    if (flag == '1') { // 提交审批
      approveInfo(record.randomFieldId, 'operate');
    }
    if (flag == '0') { // 编辑
      getContractInfo({ contractId: record.randomFieldId, operation: 'edit' }, '1', false);
    }
    if (flag == '7') { // 删除
      Modal.confirm({
        title: getLabel(15172, '系统提示'),
        content: getLabel(83600, '您确认要删除吗？'),
        okText: getLabel(33703, '确定'),
        cancelText: getLabel(201, '取消'),
        onOk() {
          deleteContract(record.randomFieldId, 'operate');
        },
        onCancel() {},
      });
    }
  }
  reRenderColumns(columns) {
    const { contractManageStore } = this.props;
    const { getContractInfo } = contractManageStore;
    columns.forEach((c) => {
      if (c.dataIndex == 'id') {
        c.render = function (text, record) {
          return <span className="nowrap crm-cursor-pointer" onClick={() => { getContractInfo({ contractId: record.id, operation: 'view' }, '1', false); }} dangerouslySetInnerHTML={{ __html: record.idspan }} />;
        };
      } else {
        c.render = function (text, record) {
          const valueSpan = record[`${c.dataIndex}span`] !== undefined ? record[`${c.dataIndex}span`] : record[c.dataIndex];
          return <span dangerouslySetInnerHTML={{ __html: valueSpan }} />;
        };
      }
    });
    return columns;
  }

  onEnterSearch=() => {
    const { contractManageStore } = this.props;
    contractManageStore.doSearch();
    contractManageStore.setShowSearchAd(false);
  }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@v60rjp`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(ContractManage);
